package com.dudu.common.util

import android.content.Context
import android.media.AudioManager
import android.provider.Settings

/**
 * <pre>
 *     author : dzc
 *     time   : 2024/10/30
 *     desc   :
 * </pre>
 */
object SystemSettingsUtil {

    /**
     * 设置屏幕亮度 0 - 255
     */
    fun setScreenBrightness(brightness: Int){
        Settings.System.putInt(applicationContext?.contentResolver, Settings.System.SCREEN_BRIGHTNESS, brightness)
    }

    /**
     * 当前音量
     */
    fun getSystemVolume(): Int{
        applicationContext?.let{
            val audioManager = it.getSystemService(Context.AUDIO_SERVICE) as AudioManager
            return audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        }
        return 0
    }

    /**
     * 最大音量
     */
    fun getSystemMaxVolume(): Int{
        applicationContext?.let{
            val audioManager = it.getSystemService(Context.AUDIO_SERVICE) as AudioManager
            return audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        }
        return 0
    }

    /**
     * getStreamMaxVolume(streamType) 返回的最大值。
     * 例如，如果 getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL) 返回15，
     * 则 index 的有效范围是0到15。
     */
    fun setSystemVolume(newVolume: Int){
        applicationContext?.let{
            val audioManager = it.getSystemService(Context.AUDIO_SERVICE) as AudioManager
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,newVolume,0)
        }
    }

    /**
     * 设置到清晰音量
     */
    fun setDistinctVolume(){
        applicationContext?.let{
            val audioManager = it.getSystemService(Context.AUDIO_SERVICE) as AudioManager
            val callVolume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL)
            val musicVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
            val callMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL)
            val musicMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
            val callTargetVolume = (callMaxVolume * 0.8).toInt()
            val musicTargetVolume = (musicMaxVolume * 0.8).toInt()
            if(callMaxVolume > 0 && callVolume < callTargetVolume){
                audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, callTargetVolume,0)
            }
            if(musicMaxVolume > 0 && musicVolume < musicTargetVolume){
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicTargetVolume,0)
            }
        }
    }

}